package com.chilly.other.jdk8.stream;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static java.awt.Color.RED;

/**
 * Created by Chilly Cui on 2021/1/7.
 */
public class StreamDemo {
    //传统方式:遍历并过滤集合
    @Test
    public void test() {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("bc");
        list.add("abc");
        list.add("bcd");
        list.add("abcd");
        //元素内容过滤
        List<String> list_a = new ArrayList<>();
        for (String s : list) {
            if (s.startsWith("a")) {
                list_a.add(s);
            }
        }
        //元素长度过滤
        List<String> list_len = new ArrayList<>();
        for (String s : list_a) {
            if (s.length() > 3) {
                list_len.add(s);
            }
        }
        //打印集合元素
        for (String s : list_len) {
            System.out.println(s); //结果:abcd
        }
    }

    //使用Steam流:遍历并过滤集合
    @Test
    public void testWithStream() {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("bc");
        list.add("abc");
        list.add("bcd");
        list.add("abcd");
        //过滤集合元素后输出
        list.stream()
                .filter(name -> name.startsWith("a")) //元素内容过滤
                .filter(name -> name.length() > 3) //元素长度过滤
                //.forEach(name -> System.out.println(name));
                .forEach(System.out::println); //结果:abcd

    }
}
